package com.test.graphsqltest.controller;

import com.test.graphsqltest.beans.GraphqlRequest;
import graphql.ExecutionInput;
import graphql.ExecutionResult;
import graphql.GraphQL;
import graphql.GraphQLError;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.annotation.Resources;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description: TODO
 * @author: wangming
 * @date: 2021年08月15日 15:57
 */
@RestController
@RequestMapping("graph")
public class GraphqController {
    @Autowired
    private GraphQL graphQL;

    @PostMapping
    public Object excute(@RequestBody GraphqlRequest graphqlRequest){

        ExecutionInput executionInput=ExecutionInput.newExecutionInput()
                .query(graphqlRequest.getQuery())
                .variables(graphqlRequest.getVariables())
                .build();
        Map<String,Object> result=new HashMap<>();
        ExecutionResult executionResult=graphQL.execute(executionInput);
        List<GraphQLError> errors=executionResult.getErrors();
        if(errors!=null&&!errors.isEmpty()){
            result.put("errors",errors);
            return result;
        }
        return executionResult.getData();
    }
}
